package ws

import(
	"fmt"
	"nightowl/logger"
	"github.com/gorilla/websocket"
	"encoding/json"
	"time"
)
type Time time.Time
const (
	//注册心跳
	MSG_TYPE_HEARTBEAT = "HEARTBEAT"
	//交付配置
	MSG_TYPE_DELIVERY_CONF = "DELIVERY_CONFIG"
	//依赖库
	MSG_TYPE_DELIVERY_LIB = "DELIVERY_LIB"
)
const (
	MSG_CODE_SUCCESS = 0
)
type EdgeClientWebSocket struct{
	Server string
	ready bool
	conn *websocket.Conn
}
type MsgClient struct{
	Id string `yaml:"id" json:"id"`
	Name string `yaml:"name" json:"name"`
	Server string `yaml:"server" json:"server"`
}
type CommonMsg struct{
	Type string `yaml:"type" json:"type"`
	Time time.Time `yaml:"time" json:"time"`
	Data interface{} `yaml:"data" json:"data"`
	From MsgClient
}
type CommonMsgResponse struct{
	Type string `yaml:"type" json:"type"`
	Time time.Time `yaml:"time" json:"time"`
	Code int `yaml:"code" json:"code"`
	Msg string `yaml:"msg" json:"msg"`
	Data interface{} `yaml:"data" json:"data"`
	From MsgClient
}
type MsgHeartBeat struct{
	Msg string `yaml:"msg" json:"msg"`
}


func (socket *EdgeClientWebSocket) listen(){
	if !socket.ready {
		logger.Error("listen|error: the websocket connection is not ready" )
	}
	// 接收消息的协程
	done := make(chan struct{})
	go func() {
		defer close(done)
		for {
			_, message, err := socket.conn.ReadMessage()
			if err != nil {
				logger.Error("读取错误:", err)
				return
			}

			// 解析服务端响应
			var resp CommonMsgResponse
			if err := json.Unmarshal(message, &resp); err != nil {
				logger.Error("解析响应失败: %v", err)
				continue
			}
			fmt.Printf("==========")
			fmt.Printf("msg response:", resp)
			fmt.Printf("==========")
			if resp.Type == MSG_TYPE_HEARTBEAT {
				if resp.Code == MSG_CODE_SUCCESS {
					logger.Info("[成功] %s\n", resp.Data)
				} else {
					logger.Error("[失败] %s\n", resp.Msg)
				}
			}
		}
	}()
}

func (socket *EdgeClientWebSocket) Init(){
	conn, _, err := websocket.DefaultDialer.Dial(socket.Server, nil)
	if err != nil {
		fmt.Printf("error:", err, socket.Server)
		logger.Error("连接失败:", err)
		return
	}
	// defer conn.Close()
	socket.conn = conn
	// fmt.Printf("conn1:", conn)
	// fmt.Printf("conn2:", socket.conn)
	socket.ready = true
	socket.listen()
	
}
func (socket *EdgeClientWebSocket)SendMsg(msgType string, data interface{}, from MsgClient){
	// fmt.Printf("conn:", socket.conn)
	// fmt.Printf("\n")
	t := time.Now()
	msg := CommonMsg{
		Type: msgType,
		Data: data,
		Time: t,
		From: from,
	}

	// fmt.Printf("msg:", msg)
	// fmt.Printf("yyy\n\n", socket.conn)
	// msgBytes, _ := json.Marshal(msg)
	// fmt.Printf("hhh\n\n", msgBytes)
	// if err := socket.conn.WriteMessage(websocket.TextMessage, msgBytes); err != nil {
	if err := socket.conn.WriteJSON(msg); err != nil {
		logger.Error("发送请求失败:", err)
	}
	// 等待响应
	time.Sleep(30 * time.Second)
}